import React, { useEffect, useState } from "react";
import { Modal, Form, Select, Button, Row, Col, Checkbox } from "antd";
import { useGetEnvironments, useGetProjects, postPermission, tryMsg } from "../../service";
import { PostPermissionParam } from "../../types";
// import { CloseOutlined } from "@ant-design/icons";

interface PermissionAddProps {
    visible: boolean;
    params :PermissionAddParam,
    onClose: () => void;
    onFlush?: (flush: boolean) => void;
}

export type PermissionAddParam = null | {
    username: string;
}

interface PermissionData {
    environments: Array<{ id: number; name: string; description: string }>;
    projects: Array<{ id: number; name: string; description: string }>;
}

const PermissionAdd: React.FC<PermissionAddProps> = ({ params, visible, onClose, onFlush }) => {
    const [form] = Form.useForm();
    const username = params.username;
    const { environments, environmentsLoading } = useGetEnvironments({});
    const { projects, projectsLoading } = useGetProjects({});
    const [permissionData, setPermissionData] = useState<PermissionData>({
        environments: [],
        projects: [],
    });

    useEffect(() => {
        if (environments && projects) {
            setPermissionData({
                environments: environments,
                projects: projects as any,
            });
        }
    }, [environments, projects]);

    const handleOk = () => {
        form.validateFields().then(async (values) => {
            tryMsg(async  ()=>{
                const { environments, projects } = values;
                const permissionCode = generatePermissionCode(environments, projects);
                permissionCode.username = username
                if(!username ){
                    throw new Error("程序异常，用户ID丢失！")
                }
                await postPermission(permissionCode);
                onFlush?.(true);
            })
        });
    };

    const handleCancel = () => {
        form.resetFields();
        onClose();
    };

    const generatePermissionCode = (environments: string[], projects: string[]): PostPermissionParam => {
        if(environments.includes("all") &&environments.length != 1 ){
            throw new Error("环境允许全部，不允许在勾选其它！")
        }
        if(projects.includes("all") &&projects.length != 1 ){
            throw new Error("项目允许全部，不允许在勾选其它！")
        }
        const envCode = environments.includes("all") ? "env:all:-1" : "env:custom:" + (environments.join(","));
        const projectCode = projects.includes("all") ? "project:all:-1" : "project:custom:" + projects.join(",");
        return {envCode:envCode,proCode:projectCode,username:''};
    };

    return (
        <Modal
            title="设置权限"
            open={visible}
            destroyOnClose={true}
            onCancel={handleCancel}
            footer={[
                <Button key="cancel" onClick={handleCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary" onClick={handleOk}>
                    提交
                </Button>,
            ]}
            // closeIcon={<CloseOutlined />}
        >
            <Form form={form} layout="vertical">
                <Form.Item name="environments" label="允许管理的环境" rules={[{ required: true, message: "请选择环境" }]}>
                    <Select
                        mode="multiple"
                        placeholder="请选择环境"
                        options={[
                            { label: "全部", value: "all" },
                            ...permissionData.environments.map((env) => ({
                                label: `${env.description}(${env.name})`,
                                value: env.id,
                            })),
                        ]}
                    />
                </Form.Item>

                <Form.Item name="projects" label="允许管理的项目" rules={[{ required: true, message: "请选择项目" }]}>
                    <Select
                        mode="multiple"
                        placeholder="请选择项目"
                        options={[
                            { label: "全部", value: "all" },
                            ...permissionData.projects.map((project) => ({
                                label: `${project.description}(${project.name})`,
                                value: project.id,
                            })),
                        ]}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default PermissionAdd;